package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(0)//过滤器顺序
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //不需要拦截的地址
        List<String> url= new ArrayList();
        url.add("/login/in");
        url.add("/v2/api-docs");
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getURI().getPath();
        //对不需要过滤的地址进行不拦截
        for (String s : url) {
            if (path.contains(s)){
               return chain.filter(exchange);
            }
        }
        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //判断token是否为空，为空的话返回缺少参数
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //解析token判断token的状态是否为-1活着0
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int code = AppJwtUtil.verifyToken(claimsBody);
            if (code==-1||code==0){
                //获取载荷中的id的值并将值放在请求头中
                Integer id = (Integer)claimsBody.get("id");
                ServerHttpRequest serverHttpRequest = request.mutate().header("id", String.valueOf(id)).build();
                exchange.mutate().request(serverHttpRequest).build();
            }

        } catch (Exception e) {
            //解析载荷错误 将返回缺少参数
            e.printStackTrace();

            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //过滤器放行
        return chain.filter(exchange);
    }
}
